import { _decorator, Node, Button, Label, Vec3 } from 'cc';
import { BasePanel } from '../../../../scripts/libs/ui/BasePanel';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { DevConfig } from '../../../../scripts/managers/DevConfig';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { ProvideInfo } from '../../../../scripts/managers/SDK/IapSDKManager';
import { find } from 'cc';
import { UIOpacity } from 'cc';
import { forkJoin, Observable, of } from 'rxjs';
import { sp } from 'cc';
import { SkeletonPlay } from '../../../../scripts/libs/rxjs/cc3/SkeletonPlay';
import { v3 } from 'cc';
import { JumpTo_2D, TweenToStart } from '../../../../scripts/libs/rxjs/cc3/TweenStart';
import { lm } from '../../LobbyManager';
import { MSResolve, MSRToString_th_m } from '../../../../scripts/libs/utils/date';
import { am } from '../../../../scripts/managers/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('GiftPackOpenPanel')
export class GiftPackOpenPanel extends BasePanel {

    key = ReactiveProperty.Create<string>(null);

    @property(Node)
    mainNode: Node = null;

    @property(sp.Skeleton)
    xslibao: sp.Skeleton = null;

    @property(Button)
    claimButton: Button = null;

    @property(Node)
    provideNode: Node = null;

    @property(Node)
    provideNode2: Node = null;

    willBind(): void {
        this.claimButton.interactable = false;
        this.claimButton.node.active = false;
        this.claimButton.getComponent(UIOpacity).opacity = 0;
        this.adaptive();
    }

    useObserves() {
        return [
            this.key.subscribe(this.refresh.bind(this)),
            BindButton(this.claimButton).subscribe(this.claimButtonClicked.bind(this)),
        ];
    }

    adaptive() {
        this.mainNode.setScale(v3(Vec3.ONE).multiplyScalar(lm.getAdaptiveScale()));
    }

    afterOpen(): Observable<string> {
        this.burstAnim();
        return of();
    }

    refresh() {
        if (this.key.value == null) return;

        if (['newbie_0', 'newbie_1'].includes(this.key.value)) {
            let info = DevConfig.iap[this.key.value];
            this.refreshProvide(info.provide);
        }
    }

    refreshProvide(provide: ProvideInfo) {

        [this.provideNode, this.provideNode2].forEach(provideNode => {
            for (let i = 0; i < provideNode.children.length; i++) {
                let node = provideNode.children[i];
                if (node.name == 'coin') {
                    if (provide.coin > 0) {
                        node.active = true;
                        node.getComponent(UIOpacity).opacity = 0;
                        find('coin/normal/Label', provideNode).getComponent(Label).string = `${provide.coin}`;
                    } else {
                        node.active = false;
                        find('coin/normal/Label', provideNode).getComponent(Label).string = '0';
                    }
                }
                if (node.name == 'swapper') {
                    if (provide.swapper > 0) {
                        node.active = true;
                        node.getComponent(UIOpacity).opacity = 0;
                        find('swapper/normal/Label', provideNode).getComponent(Label).string = `${provide.swapper}`;
                    } else {
                        node.active = false;
                        find('swapper/normal/Label', provideNode).getComponent(Label).string = '0';
                    }
                }
                if (node.name == 'magnet') {
                    if (provide.magnet > 0) {
                        node.active = true;
                        node.getComponent(UIOpacity).opacity = 0;
                        find('magnet/normal/Label', provideNode).getComponent(Label).string = `${provide.magnet}`;
                    } else {
                        node.active = false;
                        find('magnet/normal/Label', provideNode).getComponent(Label).string = '0';
                    }
                }
                if (node.name == 'balloon') {
                    if (provide.balloon > 0) {
                        node.active = true;
                        node.getComponent(UIOpacity).opacity = 0;
                        find('balloon/normal/Label', provideNode).getComponent(Label).string = `${provide.balloon}`;
                    } else {
                        node.active = false;
                        find('balloon/normal/Label', provideNode).getComponent(Label).string = '0';
                    }
                }
                if (node.name == 'inf_heart_sec') {
                    if (provide.inf_heart_sec > 0) {
                        node.active = true;
                        node.getComponent(UIOpacity).opacity = 0;
                        let msr = MSResolve(provide.inf_heart_sec * 1000);
                        find('inf_heart_sec/normal/Label', provideNode).getComponent(Label).string = MSRToString_th_m(msr);
                    } else {
                        node.active = false;
                        find('inf_heart_sec/normal/Label', provideNode).getComponent(Label).string = '0';
                    }
                }
                if (node.name == 'noads_sec') {
                    if (provide.inf_heart_sec > 0) {
                        node.active = true;
                        node.getComponent(UIOpacity).opacity = 0;
                        let msr = MSResolve(provide.noads_sec * 1000);
                        find('noads_sec/normal/Label', provideNode).getComponent(Label).string = MSRToString_th_m(msr);
                    } else {
                        node.active = false;
                        find('noads_sec/normal/Label', provideNode).getComponent(Label).string = '0';
                    }
                }
            }
        });
    }

    burstAnim() {
        SkeletonPlay(this.xslibao, 'xslibao', false).subscribe(_ => {
            this.log('SkeletonPlay next:', _);
            if (_.state == 'event' && _.event.data.name == 'burst') {
                let list: Observable<any>[] = [];

                [this.provideNode, this.provideNode2].forEach(provideNode => {
                    for (let i = 0; i < provideNode.children.length; i++) {
                        let node = provideNode.children[i];
                        if (node.active) {
                            let targetPos = v3(node.position);
                            node.setWorldPosition(this.xslibao.node.worldPosition);
                            let obs = forkJoin([
                                JumpTo_2D(node, .6, targetPos, 400, { easing: 'quadInOut' }),
                                TweenToStart(node.getComponent(UIOpacity), .2, { opacity: 255 }),
                            ]);
                            list.push(obs);
                        }
                    }
                });

                forkJoin(list).subscribe({
                    complete: () => {
                        this.claimButton.node.active = true;
                        TweenToStart(this.claimButton.getComponent(UIOpacity), .2, { opacity: 255 }).subscribe({
                            complete: () => {
                                this.claimButton.interactable = true;
                            }
                        }).addTo(this.node);
                    }
                }).addTo(this.node);

                // am.playSfx({ clipName: `ab_lobby/Audio/sfx/kaixiang` });
            }
        }).addTo(this.node);
    }

    claimButtonClicked() {
        GiftPackOpenPanel.CloseProcess(null, 'close');
    }

    // thinking(provide: ProvideInfo, type: string) {
    //     if (provide.coin > 0) {
    //         udm.temp_coin_diff.value = provide.coin ?? 0;
    //         thinking_sdk_m.requestTrack('Coins_Get', {
    //             CoinNum: provide.coin,
    //             Type: type,
    //             Gift_Detail: 'Other',
    //             IsNew: udm.isNew.value,
    //             Level_ID: udm.stageNum.value,
    //             Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
    //         });
    //     } else if (provide.swapper > 0) {
    //         thinking_sdk_m.requestTrack('Item_Get', {
    //             ItemType: 'swapper',
    //             CType: type,
    //             UseType: 'Num',
    //             ItemNum: provide.swapper,
    //             ItemAll: udm.itemSwapper.value,
    //             Level_ID: udm.stageNum.value,
    //             IsNew: udm.isNew.value,
    //             Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
    //         });
    //     } else if (provide.magnet > 0) {
    //         thinking_sdk_m.requestTrack('Item_Get', {
    //             ItemType: 'magnet',
    //             CType: type,
    //             UseType: 'Num',
    //             ItemNum: provide.magnet,
    //             ItemAll: udm.itemMagnet.value,
    //             Level_ID: udm.stageNum.value,
    //             IsNew: udm.isNew.value,
    //             Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
    //         });
    //     } else if (provide.balloon > 0) {
    //         thinking_sdk_m.requestTrack('Item_Get', {
    //             ItemType: 'balloon',
    //             CType: type,
    //             UseType: 'Num',
    //             ItemNum: provide.balloon,
    //             ItemAll: udm.itemBalloon.value,
    //             Level_ID: udm.stageNum.value,
    //             IsNew: udm.isNew.value,
    //             Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
    //         });
    //     }
    //     // TODO: 如果关卡宝箱里面有体力的奖励，也应该在此补充
    // }
}

